const qs = ele => document.querySelector(ele)
// 接口地址：https://www.apifox.cn/apidoc/shared-36f0cbc0-9064-44bc-850a-805e263bf494/api-25827426
axios.defaults.baseURL = 'http://124.223.14.236:3001/api'

async function getProvince() {
    const { data: res } = await axios.get('/city/province')
    console.log(res.data)

    const provinceStr = res.data.map((item) => `
    <option value="${item.province}">${item.name}</option>
    `).join('')
    // console.log(provinceStr)
    qs('#province').innerHTML = '<option value="">请选择省份</option>' + provinceStr
}

async function getCity(provinceCode) {
    // 获取市的数据
    const { data: { data: cityData } } = await axios.get('/city/city', {
        params: {
            provinceCode,
        },
    })
    console.log(cityData);
    const cityStr = cityData.map((item) => `
    <option value="${item.city}">${item.name}</option>
    `).join('')
    qs('#city').innerHTML = '<option value="">请选择城市</option>' + cityStr
}

async function getArea(provinceCode, cityCode) {
    // 获取区的数据
    const { data: { data: areaData } } = await axios.get('/city/area', {
        params: {
            provinceCode,
            cityCode,
        },
    })
    // console.log(areaData);
    const areaStr = areaData.map((item) => `
    <option value="${item.area}">${item.name}</option>
    `).join('')
    qs('#county').innerHTML = '<option value="">请选择区县</option>' + areaStr
}

async function init() {
    
    await getProvince()
    qs('#province').value = 34

    await getCity('34')
    qs('#city').value = '01'


    await getArea('34', '01')
    qs('#county').value = '02'

}
init()

// 省发生改变的时候，获取对应省的城市数据
qs('#province').addEventListener('change', async function () {
    // console.log(this.value)
    await getCity(this.value)
    qs('#county').innerHTML = '<option value="">请选择区县</option>'
})

// 城市发生改变的时候，获取对应省的区县数据
qs('#city').addEventListener('change', async function () {
    await getArea(qs('#province').value, this.value)

})